﻿using System;
using Windows.Globalization.DateTimeFormatting;
using Windows.UI.Xaml.Data;

namespace Looptribe.Moodlin8.UIHelper
{
    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string culture)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Value cannot be null.");
            }

            if (!(value is DateTime))
                throw new ArgumentException("Value must be of type DateTime,", "value");

            var dt = (DateTime)value;

            if (parameter == null)
                return DateTimeFormatter.ShortDate.Format(dt);

            switch ((string)parameter)
            {
                case "day":
                    {
                        var dateFormatter = new DateTimeFormatter("{day.integer(2)}");
                        return dateFormatter.Format(dt);
                    }
                case "month":
                    {
                        var dateFormatter = new DateTimeFormatter("{month.abbreviated(3)}");
                        return dateFormatter.Format(dt).ToUpper();
                    }
                case "year":
                    {
                        var dateFormatter = new DateTimeFormatter("{year.full}");
                        return dateFormatter.Format(dt);
                    }
                default:
                    return dt.ToString();
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, string culture)
        {
            var strValue = value as string;
            DateTime resultDateTime;
            return DateTime.TryParse(strValue, out resultDateTime) ? resultDateTime : Windows.UI.Xaml.DependencyProperty.UnsetValue;
        }
    }
}
